<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 生成随机字符串
 * @param $length @长度
 * @return null|string
 */
function getRandChar($length){
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol)-1;

    for($i=0;$i<$length;$i++){
        $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }
    return $str;
}

/**
 * 以POST方式提交数据
 * @param $url
 * @param $data
 * @return mixed
 */
function post_data($url, $data)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $res = curl_exec($ch);
    curl_close($ch);
    $res = json_decode($res, true);

    return $res;
}

/**
 * 以GET方式提交数据
 * @param $url
 * @param bool $is_json_decode
 * @return mixed
 */
function get_data($url, $is_json_decode = true)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取数据返回
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回

    $res = curl_exec($ch);
    curl_close($ch);
    $res = $is_json_decode ? json_decode($res, true) : $res;

    return $res;
}

/**
 * api统一返回格式
 * @param $code
 * @param array $data
 * @param string $msg
 * @return array
 */
function api_return($code, $data = [], $msg = 'success') {
    return ['code' => (int)$code, 'data' => $data, 'msg' => $msg];
}

/**
 * 给图片补上域名
 * @param string $img
 * @param string $default
 * @return string
 */
function get_img_url($img = '', $default = '')
{
    if (!$img)
    { // 没有图片使用默认图
        $img = PUBLIC_URL . 'static/home/images/default.png';
    } else {
        if (!preg_match('/^((https|http)?:\/\/)[^\s]+/i', $img)) // 有图片检查是否有http://
        {
            $img = config('image_host') . '/' . $img; // 没有就拼装图片地址域名
        }
    }
    return $img;
}

/**
 * 是否微信环境
 * @return bool
 */
function is_weixin()
{
    if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false)
    {
        return true;
    }
    return false;
}

/**
 * 获取短信接口返回码对应描述信息
 * @param $code
 * @return mixed
 */
function get_note_error_msg($code) {
    $msg_array = [
        101 => '无此用户',
        102 => '密码错',
        103 =>	'提交过快（提交速度超过流速限制）',
        104 =>	'系统忙（因平台侧原因，暂时无法处理提交的短信）',
        105 =>	'敏感短信（短信内容包含敏感词）',
        106 =>	'消息长度错（>536或<=0）',
        107 =>	'包含错误的手机号码',
        108 =>	'手机号码个数错（群发>50000或<=0;单发>200或<=0）',
        109 =>	'无发送额度（该用户可用短信数已使用完）',
        110 =>	'不在发送时间内',
        111 =>	'超出该账户当月发送额度限制',
        112 =>	'无此产品，用户没有订购该产品',
        113 =>	'extno格式错（非数字或者长度不对）',
        115 =>	'自动审核驳回',
        116 =>	'签名不合法，未带签名（用户必须带签名的前提下）',
        117 =>	'IP地址认证错,请求调用的IP地址不是系统登记的IP地址',
        118 =>	'用户没有相应的发送权限',
        119 =>	'用户已过期',
        120 =>	'测试内容不是白名单'
    ];
    return $msg_array[$code];
}


/**
 * 检查验证码
 * @param $code
 * @param $mobile
 * @return array
 */
function check_send_code($code, $mobile) {
    $where = ['code' => $code,'mobile' => $mobile];
    $model = model('note_code');
    $code = $model->where($where)->order('id desc')->find();
    //return ['code' => 0,'msg' => $model->getLastSql()];
    if (!$code)
        return ['code' => 0,'msg' => '验证码不存在'];
    if ($code['status'] > 0)
        return ['code' => 0,'msg' => '验证码已使用'];
    if ($code['create_time'] < (time() - 360))
        return ['code' => 0,'msg' => '验证码已过期 - ' . $code['create_time'] . ' - ' . (time() - 360)];

    // 将验证码状态改为已使用
    model('note_code')->where($where)->update(['status' => 1]);

    return ['code' => 200,'msg' => 'SUCCESS'];
}

/**
 * 获取上级市场线
 * @param $parent_mobile
 * @return array|bool
 */
function get_parents($parent_mobile) {
    $parent = model('member')->where('username', $parent_mobile)->find();
    if (!$parent) {
        return false;
    }
    return ['parents' => $parent['parents'] ? $parent['parents'] . ',' . $parent['id'] : $parent['id'],'id' => $parent['id']];
}

/**
 * 发送微信消息模板  -- 创建订单
 * @param $data
 */
function send_create_order_wechat_tmplmsg($data) {
    $options = config('wechat');
    $wechat = new \Wechat\TPWechat($options);
    $access_token = $wechat->checkAuth();
    $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
    post_data($url, $data);
}

/**
 * 获取汉字对应的首字母
 * @param $s0
 * @return null|string
 */
function getfirstchar($s0){
    $fchar = ord($s0{0});
    if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});
    $s1 = iconv("UTF-8","gb2312", $s0);
    $s2 = iconv("gb2312","UTF-8", $s1);
    if($s2 == $s0){$s = $s1;}else{$s = $s0;}
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if($asc >= -20319 and $asc <= -20284) return "A";
    if($asc >= -20283 and $asc <= -19776) return "B";
    if($asc >= -19775 and $asc <= -19219) return "C";
    if($asc >= -19218 and $asc <= -18711) return "D";
    if($asc >= -18710 and $asc <= -18527) return "E";
    if($asc >= -18526 and $asc <= -18240) return "F";
    if($asc >= -18239 and $asc <= -17923) return "G";
    if($asc >= -17922 and $asc <= -17418) return "H";
    if($asc >= -17417 and $asc <= -16475) return "J";
    if($asc >= -16474 and $asc <= -16213) return "K";
    if($asc >= -16212 and $asc <= -15641) return "L";
    if($asc >= -15640 and $asc <= -15166) return "M";
    if($asc >= -15165 and $asc <= -14923) return "N";
    if($asc >= -14922 and $asc <= -14915) return "O";
    if($asc >= -14914 and $asc <= -14631) return "P";
    if($asc >= -14630 and $asc <= -14150) return "Q";
    if($asc >= -14149 and $asc <= -14091) return "R";
    if($asc >= -14090 and $asc <= -13319) return "S";
    if($asc >= -13318 and $asc <= -12839) return "T";
    if($asc >= -12838 and $asc <= -12557) return "W";
    if($asc >= -12556 and $asc <= -11848) return "X";
    if($asc >= -11847 and $asc <= -11056) return "Y";
    if($asc >= -11055 and $asc <= -10247) return "Z";
    return null;
}

/**
 * 获取字符串首字母
 * @param $zh
 * @return string
 */
function pinyin1($zh){
    $ret = "";
    $s1 = iconv("UTF-8","gb2312", $zh);
    $s2 = iconv("gb2312","UTF-8", $s1);
    if($s2 == $zh){$zh = $s1;}
    for($i = 0; $i < strlen($zh); $i++){
        $s1 = substr($zh,$i,1);
        $p = ord($s1);
        if($p > 160){
            $s2 = substr($zh,$i++,3);
            $ret .= getfirstchar($s2);
        }else{
            $ret .= $s1;
        }
    }
    return $ret;
}

/**
 * 获取远程图片保存到本地
 * @param string $url
 * @远程图片地址
 * @param string $fileDir
 * @本地图片保存路径
 * @param string $fileName
 * @本地图片名称
 */
function getImage($url = '', $fileDir = '', $fileName = '')
{
    if (!is_dir($fileDir))
    {
        mkdir($fileDir);
    }
    $fileName = $fileDir . $fileName;
    $ch = curl_init();
    $fp = fopen($fileName, 'wb');

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);

    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
}

/**
 * 给二维码添加logo
 * @param $qr_code_url (二维码图片地址
 * @param string $logo
 * (默认值是一张图片
 */
function erweima_add_logo($qr_code_url, $logo = '')
{
    $logo = $logo ? $logo : ROOT_PATH . 'public' . DS . 'static' . DS . 'home' . DS . 'images' . DS . 'erweima_logo.png';
    $QR = $qr_code_url; // 已经生成的原始二维码图

    if ($logo)
    {
        $QR = imagecreatefromstring(file_get_contents($QR));
        $logo = imagecreatefromstring(file_get_contents($logo));
        $QR_width = imagesx($QR); // 二维码图片宽度
        $QR_height = imagesy($QR); // 二维码图片高度
        $logo_width = imagesx($logo); // logo图片宽度
        $logo_height = imagesy($logo); // logo图片高度
        $logo_qr_width = $QR_width / 6;
        $scale = $logo_width / $logo_qr_width;
        $logo_qr_height = $logo_height / $scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
        // 重新组合图片并调整大小
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
    }
    // 输出图片
    imagepng($QR, $qr_code_url);
}

/**
 * 微信模版消息
 * @param $data
 */
function send_msg($data)
{
    $options = config('wechat');
    $wechatObj = new \Wechat\TPWechat($options);
    $access_token = $wechatObj->checkAuth();
    $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
    post_data($url, json_encode($data));
}

/**
 * 生成验证码
 */
function GetVerify(){
    $Verify = new \verify\Verify();
    $Verify->length   = 4;
    $Verify->entry();
}

/**
 * excel表格导出
 * @param string $fileName 文件名称
 * @param array $headArr 表头名称
 * @param array $data 要导出的数据
 * @author static7  */
function excelExport($fileName = '', $headArr = [], $data = []) {
    $fileName .= "_" . date("Y_m_d", \Think\Request::instance()->time()) . ".xls";
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->getProperties();
    $key = ord("A"); // 设置表头
    foreach ($headArr as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach ($data as $key => $rows) { // 行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) { // 列写入111
            $objActSheet->setCellValue(chr($span) . $column, $value);
            $span++;
        }
        $column++;
    }
    $fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
    $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename='$fileName'");
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); // 文件通过浏览器下载
    exit();
}